import os
import tkinter as tk
from datetime import datetime
import win32gui
import ctypes
from time import sleep

root = tk.Tk()
root.title("@_@")
root.geometry("145x45")
root.resizable(False, False)

n_second = 10 * 60
remaining = n_second
timer_index = 0

start_time = None

var = tk.StringVar()

def is_screen_locked():
    hwnd = ctypes.windll.User32.GetForegroundWindow()
    return hwnd == 0 or win32gui.GetWindowText(hwnd) == 'Windows 默认锁屏界面'

def new_sector():
    """reset start_time and write the previous log into history log."""

    global start_time

    start_time = datetime.now()
    last_log = ""
    try:
        with open("current.txt", "r") as f:
            last_log = f.read()
    except FileNotFoundError:
        pass

    with open("history.txt", "a") as f:
        f.write(last_log)
    
    try:
        os.remove("current.txt")
    except FileNotFoundError:
        pass

def write_current_log():
    fmt = '%Y-%m-%d_%H:%M'
    with open("current.txt", "w") as f:
        print(start_time.strftime(fmt), datetime.now().strftime(fmt), file=f)

def remaining_str():
    global remaining
    return "%02d:%02d" % divmod(remaining, 60)

def timer_tick(index):
    global remaining
    global timer_index

    if index != timer_index: return

    once_locked = False
    while is_screen_locked():
        sleep(1)
        once_locked = True
    if once_locked:
        new_sector()

    remaining -= 1
    var.set(remaining_str())
    if remaining > 0:
        root.after(1000, timer_tick, index)
    else:
        root.wm_attributes("-fullscreen", True)
    
    if remaining % 60 == 0:
        write_current_log()

def timer_start():
    global n_second
    global remaining
    global timer_index

    remaining = n_second
    var.set(remaining_str())
    timer_index += 1
    root.after(1000, timer_tick, timer_index)
    root.wm_attributes("-fullscreen", False)
    new_sector()

frame = tk.Frame(root)

label = tk.Label(frame, textvariable=var, font=("New Courier", 28), width=6)
var.set(remaining_str())
label.pack(side="left")

button = tk.Button(frame, text="↻", command=timer_start)
button.pack(side="right")

# frame.pack()
frame.place(relx=0.5, rely=0.5, anchor="center", height=45, width=150)
#print(var.get())

#root.overrideredirect(True)
root.wm_attributes("-alpha", 0.5)
root.wm_attributes("-toolwindow", True)
root.wm_attributes("-topmost", True)

new_sector()
timer_start()

root.mainloop()
